<template>
  <div class="table-card container">
    <el-card>
      <el-form ref="searchFormRef" :model="searchData">
        <el-form-item prop="dbname" label="数据库名称：">
          <el-select v-model="searchData.dbname" placeholder="请选择" class="search-ipt">
            <el-option v-for="item in dblist" :key="item.id" :label="item.dbtitle" :value="item.dbname" />
          </el-select>
          <el-button type="primary" class="search-btn" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="openDialog" type="primary" plain
            ><el-icon><CirclePlus /></el-icon>
            <span>添加数据表</span>
          </el-button>
        </el-form-item>
      </el-form>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :row-class-name="rowClassName"
          max-height="calc(100vh - 300px)"
        >
          <el-table-column label="序号" width="60">
            <template #default="scope">
              {{ scope.row.index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="dbtitle" label="数据库名称" width="150" />
          <el-table-column prop="tname" label="表名" width="180" />
          <el-table-column label="数据表内容">
            <template #default="scope">
              <ClampText :text="scope.row.createSql" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                <el-icon color="#E34D59" size="16" @click="clickDel(scope.row)"><Delete /></el-icon>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper" v-if="paginationData.total > 0">
        <div class="totalCount">共{{ paginationData.total }}项数据</div>
        <el-pagination
          background
          :layout="paginationData.layout"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogFormVisible" title="新添加数据表" width="700">
      <el-form :model="form">
        <el-form-item label="表名称：" :label-width="formLabelWidth" style="width: 650px">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="表数据：" :label-width="formLabelWidth" style="width: 650px">
          <el-input type="textarea" :autosize="{ minRows: 8, maxRows: 10 }" v-model="form.data" autocomplete="off" />
        </el-form-item>
        <el-form-item label="" :label-width="formLabelWidth" style="width: 650px">
          <el-select v-model="form.dbname" placeholder="请选择">
            <el-option v-for="item in dblist" :key="item.id" :label="item.dbtitle" :value="item.dbname" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancle">取消</el-button>
          <el-button type="primary" @click="addTable"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue"
import { ElMessage, ElLoading, ElMessageBox } from "element-plus"
import ClampText from "@/components/ClampText/index.vue"
import { getDataList, addSqlTable, delSqlTable, getDbNameList } from "@/api/sql"
onMounted(() => {
  getTableData()
  getdblist()
})

const searchFormRef = ref(null)
const searchData = ref({
  dbname: ""
})
const handleSearch = () => {
  paginationData.value.currentPage
  getTableData()
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

const dblist = ref([])
async function getdblist() {
  const { code, data } = await getDbNameList()
  if (code === 200) {
    dblist.value = data
  }
}
const paginationData = ref({
  layout: "prev, pager, next",
  total: 0,
  pageSize: 10,
  currentPage: 1
})
const handleCurrentChange = (val) => {
  if (paginationData.value.currentPage === val) return
  paginationData.value.currentPage = val
  getTableData()
}

const dialogFormVisible = ref(false)
const form = ref({
  name: "",
  data: "",
  dbname: ""
})
const formLabelWidth = "80px"
const tableData = ref([])

async function getTableData() {
  const wrap = document.getElementsByClassName("table-wrapper")[0]
  const loadingInstance = ElLoading.service({
    target: wrap,
    text: "Loading"
  })
  const { code, data } = await getDataList({
    dbname: searchData.value.dbname,
    page: paginationData.value.currentPage,
    pageSize: paginationData.value.pageSize
  })
  if (code === 200) {
    tableData.value = data.resultList
    paginationData.value.total = data.totalCount
  }
  loadingInstance.close()
}
const clickDel = (para) => {
  ElMessageBox.confirm("确认删除当前数据吗?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delTr(para)
  })
}
async function delTr(row) {
  const { code } = await delSqlTable({ tid: row.tid })
  if (code === 200) {
    ElMessage.success("删除成功")
    tableData.value.splice(row.index, 1)
  }
}
function rowClassName({ row, rowIndex }) {
  row.index = rowIndex
}

function openDialog() {
  dialogFormVisible.value = true
}
function cancle() {
  form.value.name = ""
  form.value.data = ""
  form.value.dbname = ""
  dialogFormVisible.value = false
}
async function addTable() {
  const { code } = await addSqlTable({
    tname: form.value.name,
    createSql: form.value.data,
    dbname: form.value.dbname
  })
  if (code === 200) {
    ElMessage.success("添加成功")
    tableData.value.push({
      tname: form.value.name,
      createSql: form.value.data,
      dbname: form.value.dbname
    })
    form.value.name = ""
    form.value.data = ""
    form.value.dbname = ""
    dialogFormVisible.value = false
  }
}
</script>
<style lang="scss" scoped>
/* 设置表头背景色 */
::v-deep(.el-table__header-wrapper th) {
  background-color: #f5f5f5; /* 背景色 */
  color: #333; /* 文字颜色 */
  font-weight: bold; /* 加粗字体 */
}
.search-btn {
  margin-left: 16px;
}
.search-ipt {
  width: 250px;
}
.table-card {
  padding-bottom: 20px;
}
.add-wrap {
  padding: 20px;
  display: flex;
}

.table-wrapper {
  margin-bottom: 20px;
}
.pager-wrapper {
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
